import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { Outlet } from "react-router";
import ROSLIB from "roslib";
import { RosContext } from "../context";
import styles from "../styles/Root.module.css";

export default function Root() {
  const ros = useRos();
  const timeEle = useRef<HTMLDivElement>(null);
  const dateEle = useRef<HTMLDivElement>(null);

  // 设置网页时间
  useEffect(() => {
    const nums = ["日", "一", "二", "三", "四", "五", "六"];
    const it = setInterval(() => {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const date = now.getDate();
      const day = now.getDay();
      const hour = now.getHours().toString().padStart(2, "0");
      const min = now.getMinutes().toString().padStart(2, "0");
      const sec = now.getSeconds().toString().padStart(2, "0");
      dateEle.current!.textContent = `${year}年${month}月${date}日 星期${nums[day]}`;
      timeEle.current!.textContent = `${hour}:${min}:${sec}`;
    }, 1000);
    return () => {
      clearInterval(it);
    };
  }, []);

  return (
    ros && (
      <RosContext.Provider value={ros}>
        <header className={styles.header}>
          <div className={styles.tool}>
            <div ref={timeEle} className={styles.time}></div>
            <div ref={dateEle} className={styles.date}></div>
          </div>
          <div className={styles.title}>无人系统算法评估平台</div>
          <ul className={styles.nav}>
            <li className={styles.navItem}>
              <div className={styles.active}>集群博弈</div>
            </li>
            <li className={styles.navItem}>
              <div>路径规划</div>
            </li>
            <li className={styles.navItem}>
              <div>视觉感知</div>
            </li>
          </ul>
        </header>

        <main className={styles.main}>
          <Outlet />
        </main>
        <footer className={styles.footer}>
          <div className={styles.sysInfo}></div>
          <div className={styles.bar}></div>
        </footer>
      </RosContext.Provider>
    )
  );
}

function useRos() {
  const [ros, setRos] = useState<ROSLIB.Ros>();
  useLayoutEffect(() => {
    const ros = new ROSLIB.Ros({
      url: "ws://localhost:9090",
    });

    ros.on("connection", function () {
      console.log("Connected to websocket server.");
    });
    ros.on("error", function (error) {
      console.log("Error connecting to websocket server: ", error);
    });
    ros.on("close", function () {
      console.log("Connection to websocket server closed.");
    });
    setRos(ros);

    return () => {
      ros.close();
    };
  }, []);
  return ros;
}
